import {computed, reactive} from "plain-ui-composition";

const SEPARATOR_WIDTH = 4

export function useRunSeparator() {

    const state = reactive({
        codeWidth: window.screen.width / 2,
        dragWidth: window.screen.width / 2,
    })

    const dragState = {
        startX: 0,
        moveX: 0,
        startWidth: 0,
    }

    const styles = computed(() => {
        return {
            code: {
                width: `${state.codeWidth}px`,
            },
            case: {
                left: `${state.codeWidth}px`,
            },
            separator: {
                left: `${state.dragWidth - SEPARATOR_WIDTH / 2}px`,
                width: `${SEPARATOR_WIDTH}px`
            }
        }
    })

    const handler = {
        mousedown: (e: MouseEvent) => {
            dragState.startX = dragState.moveX = e.clientX
            dragState.startWidth = state.codeWidth

            window.addEventListener('mousemove', handler.mousemove)
            window.addEventListener('mouseup', handler.mouseup)
        },
        mousemove: (e: MouseEvent) => {
            dragState.moveX = e.clientX
            state.dragWidth = dragState.startWidth + (dragState.moveX - dragState.startX)
        },
        mouseup: () => {
            state.codeWidth = state.dragWidth
            window.removeEventListener('mousemove', handler.mousemove)
            window.removeEventListener('mouseup', handler.mouseup)
        }
    }

    const render = () => <div class="app-run-separator" style={styles.value.separator} onMousedown={handler.mousedown}/>

    return {
        render,
        styles,
    }
}
